const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const _ = require('lodash');

function insertBuilding(ctx,newBuilding,house_create_time,house_update_time,total_unit,total_floor,per_floor_household,default_house_type_id){
    return new Promise((resolve, reject) => {
        var trans = mysql.Client.startTransaction();
        trans.query(`INSERT INTO building SET ?`, newBuilding, function(err, info) {
            if(err){
                trans.rollback();
                ctx.body = {
                    result: 202,
                    message: "新增楼幢失败"
                };
                resolve(ctx);
            } else{
                let insertHouses = `INSERT INTO house (house_name, house_type_id, building_id, floor, unit, household_num, status, is_model_house, house_create_time, house_update_time) VALUES `;
                for(i = 0; i < total_unit; i++) {
                    for (j = 0; j < total_floor; j++){
                        for (k = 0; k < per_floor_household; k++){
                            insertHouses += `('${k+1}号', ${default_house_type_id}, ${info.insertId}, ${j+1}, ${i+1}, ${k+1}, 0, 0,  '${house_create_time}', '${house_update_time}'),`;
                        }
                    }
                }
                housesSql = insertHouses.substr(0,insertHouses.length-1);
                trans.query(housesSql, function(err) {
                    if(err){
                        trans.rollback();
                        ctx.body = {
                            result: 202,
                            message: "新增楼幢失败"
                        };
                    } else{
                        trans.commit();
                        ctx.body = {
                            result: 200,
                            id: info.insertId,
                            message: "新增楼幢成功"
                        };
                    }
                    resolve(ctx);
                });
            }
        });
        trans.execute();
    });
};
exports.add = async(ctx) => {
    let building_name = ctx.request.body.building_name || '';
    let project_id = ctx.request.body.project_id || 0;
    let total_unit = ctx.request.body.total_unit || 0;
    let total_floor = ctx.request.body.total_floor || 0;
    let per_floor_household = ctx.request.body.per_floor_household || 0;
    let total_household = per_floor_household * total_floor * total_unit;
    let default_house_type_id = ctx.request.body.default_house_type_id || 0;
    if (building_name === '' || default_house_type_id <= 0 || project_id <= 0 || total_unit <= 0 || total_floor <= 0 || total_household <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let existproject = await mysql.query(`SELECT * FROM project WHERE project_id = ?`, project_id);
        if (existproject.length <= 0){
            ctx.body = {
                result: 203,
                message: "找不到对应项目"
            };
            return
        }
        let existhousetype = await mysql.query(`SELECT * FROM house_type WHERE house_type_id = ?`, default_house_type_id);
        if (existhousetype.length <= 0){
            ctx.body = {
                result: 204,
                message: "找不到对应户型"
            };
            return
        }
        let building_create_time = moment().format('YYYY-MM-DD HH:mm:ss');
        let building_update_time = moment().format('YYYY-MM-DD HH:mm:ss');
        let newBuilding = {
            building_name,
            project_id,
            total_unit,
            total_floor,
            total_household,
            building_create_time,
            building_update_time,
            is_deleted:0,
            status:0
        };
        let house_create_time = moment().format('YYYY-MM-DD HH:mm:ss');
        let house_update_time = moment().format('YYYY-MM-DD HH:mm:ss');
        await insertBuilding(ctx,newBuilding,house_create_time,house_update_time,total_unit,total_floor,per_floor_household,default_house_type_id);

        // ret = mysql.Client.query('SELECT * FROM building');
        // console.log('ret:',ret)
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "新增楼幢失败"+e.toString()
        };
    }
}

exports.delete = async(ctx) => {
    let building_id = ctx.params.building_id || 0;
    if (building_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        selectRows = await mysql.query(`SELECT * from building WHERE building_id = ? `, building_id);
        if (selectRows.length > 0){
            selectRows[0].is_deleted = 1;
            ret = await mysql.query(`UPDATE building SET ? WHERE building_id = ? `, [selectRows[0],building_id]);
            if (!ret || ret.insertId === -1){
                ctx.body = {
                    result: 202,
                    message: "删除失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "删除成功"
                };
            }
        } else{
            ctx.body = {
                result: 203,
                message: "删除失败，对象不存在或已删除"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let building_id = ctx.request.body.building_id || 0;
    let house_type_name = ctx.request.body.house_type_name || '';
    // let project_id = ctx.request.body.project_id || 0;
    let area = ctx.request.body.area || '';
    if (house_type_id <= 0 || house_type_name === '' || area === '') {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let selectRows = await mysql.query(`SELECT * FROM house_type WHERE house_type_id = ?`, house_type_id);
        if (selectRows.length > 0) {
            console.log('selectRows:', selectRows);
            selectRows[0].house_type_name = house_type_name;
            selectRows[0].area = area;
            ret = await mysql.query(`UPDATE house_type SET ? WHERE building_id = ?`, [selectRows[0],building_id]);
            if (!ret || ret.insertId === -1) {
                ctx.body = {
                    result: 202,
                    message: "更新失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "更新成功"
                };
            }
        } else {
            ctx.body = {
                result: 203,
                message: "对象不存在或者已删除"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "删除失败"+e.toString()
        };
    }
}

exports.getList = async(ctx) => {
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;
    let project_id = ctx.params.project_id || 0;

    if (project_id <= 0){
        ctx.body = {
            result: 201,
            message: "无效的project_id"
        };
        return;
    }
    try {
        results = await mysql.query(`SELECT * FROM building WHERE project_id = ${project_id} and is_deleted = 0 ORDER BY building_id LIMIT ${indexfrom}, ${counts} ` );
        let totalResult = await mysql.query(`SELECT COUNT(building_id) AS total FROM building WHERE project_id = ${project_id} and is_deleted = 0 `);
        ctx.body = {
            result: 200,
            list:results,
            totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
            totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
            message: "查询成功"
        };
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}